package com.amumu.drama.common.config.redis;

import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * JedisTemplate 注入配置
 */
@Slf4j
@Component
public class JedisTemplateRegistrar {

    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisTemplate jedisTemplate() {
        return new JedisTemplate(createJedisPool(redisProperties));
    }

    /** 创建 JedisPool */
    private static JedisPool createJedisPool(RedisProperties redisProperties) {
        String clientName = System.getProperty("app.id");
        JedisPoolConfig poolConfig = null;
        if (poolConfig == null) {
            poolConfig = new JedisPoolConfig();
            poolConfig.setMaxTotal(64);
            poolConfig.setMaxIdle(64);
            poolConfig.setMinIdle(4);
        }
        return new JedisPool(poolConfig,
                redisProperties.getHost(),
                redisProperties.getPort(),
                NumberUtil.parseInt(redisProperties.getTimeout().getNano() / 1000000 + ""),
                redisProperties.getPassword(),
                redisProperties.getDatabase(),
                clientName
        );
    }

}
